const path = require('path');
const multer = require('multer');

// 前端上传图片名称必须与single内的名称一致，否则就报错；
const upload = (Path) => {
    let storage = multer.diskStorage({
        // 文件上传的位置
        //设置存储路径
        destination: (req, file, cb) => {
            // console.log("destination:", file);//打印结果如下图
            // req.file = file;
            cb(null, Path);
        },
        fileFilter(req, file, cb) {
            // 解决中文名乱码的问题
            file.originalname = Buffer.from(file.originalname, "latin1").toString(
                "utf8"
            );
            // console.log('file.originalname', file.originalname)
            let extName = path.extname(file.originalname)
            if (extName.includes('.png') || extName.includes('.jpg') || extName.includes('.jpeg') || extName.includes('.gif') || extName.includes('.webp') || extName.includes('.mp4')) {
                cb(null, true)
            } else {
                // req.fileCheckError = {}
                // req.fileCheckError['fileFilter'] = '只能上传png格式的文件'
                cb(null, false)
            }
        },

        filename(req, file, cb) {
            // 解决中文名乱码的问题
            file.originalname = Buffer.from(file.originalname, "latin1").toString(
                "utf8"
            );
            console.log('file.originalname', file)
            cb(null, file.originalname);
        }
    });
    return multer({ storage }).single('file')

}

module.exports = upload;